require('../common/utils.js')
const { useEnv } = require('../starter/init.js')


var Docker = require('dockerode');
var docker = new Docker({
  host: useEnv.DOCKER_HOST || '172.88.0.41',
  port: useEnv.DOCKER_PORT || 2375,
});


function build(){
  var DOCKER_IMAGE_TAG = useEnv.DOCKER_IMAGE_TAG || 'v1';
  if (useEnv.DOCKER_IMAGE_TAG) {
    DOCKER_IMAGE_TAG = eval(useEnv.DOCKER_IMAGE_TAG);
  }

  let imageName = useEnv.DOCKER_IMAGE_NAME + ':' + DOCKER_IMAGE_TAG;
  console.log('开始构建镜像: ', imageName);
  docker.buildImage({
    context: process.cwd(),
    src: ['docker', 'dist']
  }, {
    t: imageName,
    dockerfile: useEnv.DOCKER_DOCKERFILE
  }, function (err, response){
    if (err){
      console.log('构建镜像时错误');
      console.error(err);
      return;
    }

    let isErr = false;

    docker.modem.followProgress(response, (err) => {
      if (err || isErr) {
        console.error('构建镜像时错误', err || '');
      } else {
        console.log('构建镜像完成');
        push(imageName);
      }
    }, function (obj) {
      if (obj.error) {
        console.error(obj.error);
        isErr = true;
      } else if (obj.aux) {
        console.log(obj.aux);
      } else {
        console.log(obj.stream);
      }
    });

  });

}

// 发布到前端
function push(imageName){

  console.log('\n\n开始PUSH镜像: ', imageName);

  docker.getImage(imageName).push({
    authconfig: {
      username: useEnv.DOCKER_USERNAME,
      password: useEnv.DOCKER_PASSWORD,
    }
  }, function(err, stream){
    if (err) {
      console.log('push镜像时错误');
      console.error(err);
      return;
    }

    let isErr = false;
    docker.modem.followProgress(stream, (err, res) => {
      if (err || isErr) {
        console.error('push镜像时错误', err || '');
      } else {
        console.log('\n\npush镜像完成\n\n');
      }
    }, function (obj) {
      if (obj.error) {
        console.error(obj.error);
        isErr = true;
      } else if (obj.aux) {
        console.log(obj.aux.Tag, obj.aux.Size, obj.aux.Digest);
      } else {
        console.log(obj.id || '', obj.status, obj.progress || '');
      }
    });

  });
}






// eslint-disable-next-line no-unused-vars
function date(fmt='yyyyMMdd.HH.mm'){
  return new Date().Format(fmt);
}


module.exports = {
  build,
  push
}
